<?php
/**
 * 投保记录
 * @Author    紫梦
 * @DateTime  2018-01-17
 * @copyright 响响租车
 * @version   1.0
 */
namespace app\index\controller;
use think\Exception;
use \think\Request;
use \think\Db;
use app\common\model\Secure as SecureModel;
use app\common\model\Cars;
use app\common\request\Oss;
use app\common\controller\Execl;

class Secure extends Base
{
	public function index()
	{
        $request = Request::instance();
        
        if($request->isAjax()){
            $post = $request->post();
            if( !empty($post['secure_end']) ){
                $where['secure_end'] = ['<= time',$post['secure_end']];
                $where['status'] = 1;
            }
            if( !empty($post['secure_type']) ){
                $where['secure_type'] = $post['secure_type'];
            }
            if( !empty($post['secure_company']) ){
                $where['secure_company'] = $post['secure_company'];
            }
            if( !empty($post['search_inpute']) ){
                $car_id = Cars::where( ['car_sn|car_unique_id' => ['like','%'.$post['search_inpute'].'%']] )
                                ->column('car_id');               
                $where['car_id'] = ['in',$car_id];

            }
            
            if( !empty($post['status']) ){
                $where['status'] = $post['status'];
            }
            if( empty($where) ){
                $where = '1=1';
            }        
            $model= SecureModel::with('agency')->where($where)
                            ->order('status asc,warn desc,id desc')
                            ->paginate($post['length'],false,[
                                    'type'     => 'bootstrap',
                                    'var_page' => 'page',
                                    'page'=>$post['start']/$post['length'] +1 ,
                                ]);


            if(count($model)>=1){

                foreach ($model as $key => $value) {
                    
                   $value['cars_info'] = $value->car_id;
                    $res['data'][] = $value;
                }
               
                $res['recordsTotal'] = $res['recordsFiltered'] = $model->total();
            }else{
                    $res['data']= '';
                    $res['recordsTotal'] = $res['recordsFiltered'] =0;
            }
            
            return $res;

        }else{

            return $this->fetch();
        }
	}

    /**
     * 添加投保记录
     */
    public function add()
    {
        $request = Request::instance();

        if($request->isAjax()){
            $data = $request->post();
            //车辆ID
            $car = Cars::get(['car_sn'=>$data['car_sn']]);
            if(!$car){
                $msg['status'] = 1;
                $msg['msg'] = '车牌号不存在,请查正后再添加';
                return $msg;
            }
            $data['car_id'] = $car['car_id'];
            $id = SecureModel::where([
                        'car_id' => $car['car_id'],
                        'secure_type'=> $data['secure_type'],
                        'secure_end'=>['<= time',$data['secure_end']],
                        'status' => 1,
                        'notice' => 1
                        ])->value('id'); 
            $model = new SecureModel();                   
            if($id){
                //有的话添加并更新  1将状态更改为已更新 2提醒需求取消      
                try {
                    $result = $model->allowField(true)
                        ->validate(
                            [
                                'secure_end'  => 'after:'.date('Y-m-d').''
                            ],
                            [
                                'secure_end' => '到期日小于今日'
                            ]
                         )->save($data);
                    $model->where('id', $id)
                            ->update([
                                'status' => 2,
                                'notice' => 2,
                                'warn' => 2
                            ]);       
                } catch (Exception $e) {
                    return [
                        'code'=>3,
                        'msg'=>$e->getMessage()
                        ];     
                }      
            }else{
                //没有的话只添加
                try {
                   $result = $model->allowField(true)
                        ->validate(
                            [
                                'secure_end'  => 'after:'.date('Y-m-d').''
                            ],
                            [
                                'secure_end' => '到期日小于今日'
                            ]
                         )->save($data);                    
                } catch (Exception $e) {
                    return [
                        'code'=>3,
                        'msg'=>$e->getMessage()
                        ];
                }

            }
            if(false === $result){
                // 验证失败 输出错误信息
                return [
                    'code'=>2,
                    'msg'=>$model->getError(),
                ];
            }
            //电子文件
            $uploadfile = $request->file('uploadfile');
            if($uploadfile){
                $oss = new Oss();
                foreach ($uploadfile as $key => $value) {
                    $url = $oss->uploadOss($value);                 
                    if($url){
                        Db::name('secure_file')->insert(['secure_id'=>$model->id,'file_url'=>$url]);
                    }
                }
            }

            return [
                'code'=>1,
                'msg'=>'添加成功'
                ];

        }else{
            return $this->fetch();

        }

    }	

    /**
     * 编辑投保记录
     */
    public function edit($id)
    {
        $request = Request::instance();

        if($request->isAjax()){
            $data = $request->post();
            //车辆ID
            $car = Cars::get(['car_sn'=>$data['car_sn']]);
            if(!$car){
                $msg['status'] = 1;
                $msg['msg'] = '车牌号不存在,请查正后再添加';
                return $msg;
            }
            $data['car_id'] = $car['car_id'];
            $model = new SecureModel();

            try {
               $result = $model->allowField(true)
                    ->validate(
                        [
                            'secure_end'  => 'after:'.date('Y-m-d').''
                        ],
                        [
                            'secure_end' => '到期日小于今日'
                        ]
                     )->isUpdate(true)->save($data);                    
            } catch (Exception $e) {
                return [
                    'code'=>3,
                    'msg'=>$e->getMessage()
                    ];
            }
            if(false === $result){
                // 验证失败 输出错误信息
                return [
                    'code'=>2,
                    'msg'=>$model->getError(),
                ];
            }
            //电子文件
            $uploadfile = $request->file('uploadfile');
            if($uploadfile){
                $oss = new Oss();
                foreach ($uploadfile as $key => $value) {
                    $url = $oss->uploadOss($value);                 
                    if($url){
                        Db::name('secure_file')->insert(['secure_id'=>$data['id'],'file_url'=>$url]);
                    }
                }
            }
            return [
                'code'=>1,
                'msg'=>'更新成功'
            ];
        }else{
            $model = SecureModel::get($id);
            $this->assign('data',$model);
            return $this->fetch();

        }
    } 

    /**
     * 删除记录
     */
    public function delete($id)
    {
        try {
            SecureModel::destroy($id);
            
        } catch (\Exception $e) {
            return [
                'code'=>2,
                'msg'=>$e->getMessage()
                ];
            
        }
        
        return [
            'code'=>1,
            'msg'=>'删除成功'
            ];
    }

    /**
     * 删除附件
     */
    public function del_file($id)
    {        
        $url = Db::name('secure_file')->where(['id'=>$id])->find();
        $oss = new Oss();
        $res = false;
        if($oss->unlinkOss($url['file_url'])){           
            try {
                Db::name('secure_file')->delete($id);
            } catch (Exception $e) {
                return [
                    'code'=>2,
                    'msg'=>$e->getMessage(),
                    ];
            }
            
        }
        return [
            'code'=>1,
            'msg'=>'删除成功'
            ];
    }  

    /**
     * 基础数据导入
     */
    public function excel_data()
    {
        $request = Request::instance();
        if($request->isPost()){
            $file = $request->file('excel');
            if($file){
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if($info){
                    // 成功上传后 获取上传信息
                    $url = $info->getSaveName();
                    $ext = $info->getExtension();
                    $path = ROOT_PATH . 'public' . DS . 'uploads/'.$url;
                    $excel = new Execl;
                    $excelData = $excel->readerBase($path);
                    
                    if(empty($excelData)){
                        return [
                            'code'=>2,
                            'msg'=>'数据格式不合法'
                            ]; 
                    }
                    $insertNum = 0;
                    // 遍历数据加入到数据库中去 
                    foreach ($excelData as $key => $value) {
                        if($key==0){
                            continue;
                        }else{
                            $data['car_sn'] = trim($value[0]??'');                            
                            switch (trim($value[1]??'')) {
                                case '交强险':
                                    
                                    $data['secure_type'] = 1;
                                    break;
                                case '商业保险':
                                    
                                    $data['secure_type'] = 2;
                                    break;
                                case '承运人责任险':
                                    
                                    $data['secure_type'] = 3;
                                    break;  
                                default:
                                    $data['secure_type'] = 0;
                                    break;
                            }
                            switch (trim($value[2]??'')) {
                                case '平安保险':
                                    
                                    $data['secure_company'] = 1;
                                    break;
                                case '阳光保险':
                                    
                                    $data['secure_company'] = 2;
                                    break;
                                case '中银保险':
                                    
                                    $data['secure_company'] = 3;
                                    break;
                                case '中保保险':
                                    
                                    $data['secure_company'] = 4;
                                    break;
                                case '中华联合保险':
                                    
                                    $data['secure_company'] = 5;
                                    break;

                                case '太平洋保险':
                                    
                                    $data['secure_company'] = 6;
                                    break;
                                case '都邦财产保险':
                                    
                                    $data['secure_company'] = 7;
                                    break;  
                                default:
                                    $data['secure_company'] = 0;
                                    break;
                            }
                            if( is_numeric($value[3]??'') ){
                                $data['secure_start'] = date('Y-m-d',($value[3]-25569)*24 * 60 * 60);
                            }else{
                                $star = $value[3]??'';
                                if( is_object($star) ){

                                    $data['secure_start'] = $star->__toString(); 
                                }else{
                                    $data['secure_start'] = $star;
                                }
                            }
                            if(is_numeric($value[4]??'')){
                                $data['secure_end'] = date('Y-m-d',($value[4]-25569)*24 * 60 * 60);
                            }else{
                                $end = $value[4]??'';
                                if( is_object($end) ){

                                    $data['secure_end'] = $end->__toString(); 
                                }else{
                                    $data['secure_end'] = $end;
                                }
                            }
                            $data['secure_money'] = floatval($value[5]??'');
                            $data['secure_desc'] = trim($value[6]??'');
                            $res = self::data_add($data);
                            if($res['code']==1){
                                $insertNum++;
                            }

                        }

                    }
                }else{
                   return [
                    'code'=>2,
                    'msg'=>$file->getError()
                    ]; 
                }
            }else{
               return [
                    'code'=>2,
                    'msg'=>'没有文件被上传'
                    ]; 
            }

            return [
                'code'=>1,
                'msg'=>'添加了'.$insertNum.'条数据'
                ]; 
        }else{
            return $this->fetch();
        }
    }  

    /**
     * 空表
     */
    public function excel_null()
    {
        Execl::secure_excel();       
    }

    private static function data_add($data)
    {
        $car = Cars::get(['car_sn'=>$data['car_sn']]);
        if(!$car){
            return [
                'code'=>2,
                'msg'=>'车牌不存在'
            ];
        }
        $data['car_id'] = $car['car_id'];
        $id = SecureModel::where([
                    'car_id' => $car['car_id'],
                    'secure_type'=> $data['secure_type'],
                    'secure_end'=>['<= time',$data['secure_end']],
                    'status' => 1,
                    'notice' => 1
                    ])->value('id'); 
        $model = new SecureModel();                   
        if($id){
            //有的话添加并更新  1将状态更改为已更新 2提醒需求取消      
            try {
                $result = $model->allowField(true)
                    ->validate(
                        [
                            'secure_end'  => 'after:'.date('Y-m-d').''
                        ],
                        [
                            'secure_end' => '到期日小于今日'
                        ]
                     )->save($data);
                $model->where('id', $id)
                        ->update([
                            'status' => 2,
                            'notice' => 2,
                            'warn' => 2
                        ]);       
            } catch (Exception $e) {
                return [
                    'code'=>3,
                    'msg'=>$e->getMessage()
                    ];     
            }      
        }else{
            //没有的话只添加
            try {
               $result = $model->allowField(true)
                    ->validate(
                        [
                            'secure_end'  => 'after:'.date('Y-m-d').''
                        ],
                        [
                            'secure_end' => '到期日小于今日'
                        ]
                     )->save($data);                    
            } catch (Exception $e) {
                return [
                    'code'=>3,
                    'msg'=>$e->getMessage()
                    ];
            }

        }
        if(false === $result){
            // 验证失败 输出错误信息
            return [
                'code'=>2,
                'msg'=>$model->getError(),
            ];
        }

        return [
                'code'=>1,
                'msg'=>'添加成功'
                ]; 
    }
      
}